import * as QuarkGIS from "quarkgis";
import "./Popup.scss";

export function initPopup(viewer) {
    var that = this;
    if (that.isInit) {
        return 0;
    }
    var frameDiv = viewer.quarkgisWidget.container
    //弹窗容器div
    var rightdiv = document.createElement('DIV');
    rightdiv.className = "quarkgis_popup_box";

    that.viewer = viewer;
    that.addDiv = rightdiv;
    frameDiv.appendChild(rightdiv);

    that.isInit = true;


}

export function setPopupHtml(html) {
    var that = this;
    if (!that.isInit) {
        return 0;
    }
    that.addDiv.innerHTML = html;
}

//控制弹窗定位
export function showPopupAt(position) {

    var that = this;
    if (!that.isInit) {
        return 0;
    }
    if (position) {
        that.setPopupVisible(true);
        that.addDiv.style.left = position.x + "px";
        that.addDiv.style.top = (position.y - 150) + "px";
    }
}

export function bindEventListener(position) {
    var that = this;
    var ellipsoid = that.viewer.scene.globe.ellipsoid;
    var cartesian = that.viewer.camera.pickEllipsoid(position, ellipsoid);
    var cartographic = QuarkGIS.Cartographic.fromCartesian(cartesian);

    var lon = QuarkGIS.Math.toDegrees(cartographic.longitude);
    var lat = QuarkGIS.Math.toDegrees(cartographic.latitude);

    var point2 = {longitude: lon, latitude: lat};
    that.click_point = QuarkGIS.Cartesian3.fromDegrees(point2.longitude, point2.latitude);
    // console.log(that.click_point)

    that.c = new QuarkGIS.Cartesian2(position.x, position.y);
    that.target_position = position
    that.cartesian_2 = cartesian
    that.viewer.scene.camera.moveStart.addEventListener(() => {
        that.removeHandler = that.viewer.scene.postRender.addEventListener(() => {
            if (that.getPopupVisible()) {
                if (that.c) {
                    that.changedC = QuarkGIS.SceneTransforms.wgs84ToWindowCoordinates(that.viewer.scene, that.cartesian_2);
                    that.showPopupAt(that.changedC)
                    that.c = that.changedC
                }
            }
        })
    })
    //相机移动结束事件
    that.viewer.scene.camera.moveEnd.addEventListener(() => {
        if (that.removeHandler) {
            that.removeHandler.call();
        }
    })
}

export function getPopupVisible() {
    var that = this;
    if (!that.isInit) {
        return false;
    }
    return that.addDiv.style.display == 'block' ? true : false;
}

export function setPopupVisible(visible) {
    var that = this;
    if (!that.isInit) {
        return 0;
    }
    that.addDiv.style.display = visible ? 'block' : 'none';
}
